<?php
namespace app\redbag\controller;

use app\ApiRest;
use app\card\model\DefaultSetting;
use app\redbag\info\PermissionRedbag;
use app\redbag\model\Img;
use app\redbag\model\Invitation;
use app\redbag\model\staffRecord;
use app\shop\controller\IndexWxPay;
use longbingcore\wxcore\WxSetting;
use think\App;
use app\redbag\model\IndexActive as Model;
use app\redbag\model\AdminCompany;
use app\redbag\model\Record;
use think\facade\Db;

class IndexActive extends ApiRest
{

    protected $model;

    protected $company_model;

    protected $record_model;

    protected $count_model;


    public function __construct(App $app) {
        parent::__construct($app);

        $this->model= new Model();

        $this->company_model= new AdminCompany();

        $this->record_model = new Record();


    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-10 09:44
     * @功能说明:员工端活动列表
     */
    public function staffActiveList(){
        //员工记录模型
        $staff_record = new staffRecord();

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.staff_id','=',$this->getUserId()];

        $dis[] = ['b.status','=',1];
        //初始化
        $staff_record->changeStatus($this->_uniacid);

        $data = $staff_record->staffRecordList($dis,$this->getUserId());

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-10 10:28
     * @功能说明:红包详情
     */
    public function activeInfo(){

        $input = $this->_input;

        $data  = $this->model->activeInfo(['id'=>$input['id']]);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-10 10:28
     * @功能说明:员工段活动详情
     */

    public function staffActiveInfo(){

        $input = $this->_param;

        $data  = $this->model->activeInfo(['id'=>$input['id']]);

        if(empty($data)){

            $this->errorMsg('红包活动未找到');
        }

        $staff_record_model = new staffRecord();

        $record_dis = [
            //员工
            'staff_id'  => $this->getUserId(),
            //活动
            'active_id' => $data['id']
        ];
        //是否开始发放
        $staff_record = $staff_record_model->recordInfo($record_dis);

        if(empty($staff_record)){

            $this->errorMsg('该员工没有此权限');

        }


        if(!empty($staff_record)){

            $data['redbag_status'] = $staff_record['status'];

            $data['is_show']       = $staff_record['is_show'];

        }

        //已经领取个数
        $record_dis = [
            //状态
            'status'    => 1,
            //员工
            'staff_id'  => $this->getUserId(),
            //活动
            'active_id' => $input['id']
        ];

        $record_model  = new Record();
        //使用数量
        $use_count = $record_model->where($record_dis)->count();
        //已经领取
        $data['use_count']   = $use_count;
        //总价
        $data['total_price'] = round($staff_record['price']*$staff_record['total_num'],2);

        $data['create_time'] = date('Y-m-d H:i:s',$staff_record['create_time']);

        $datas['info']       = $data;

        $record_dis = [
            //员工
            'a.staff_id'  => $this->getUserId(),
            //活动
            'a.active_id' => $data['id'],

            'a.status'    => 1

        ];

        $datas['get_list'] = $this->record_model->getUserList($record_dis);

        return $this->success($datas);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-10 12:00
     * @功能说明:活动详情
     */
    public function staffActiveText(){

        $input = $this->_input;

        $active= $this->model->activeInfo(['id'=>$input['id']]);

        if(empty($active)){
            $this->errorMsg('红包未找到');
        }
        $record_model  = new Record();

        //已经领取个数
        $record_dis = [
            //状态
            'status'    => 1,
            //员工
            'staff_id'  => $this->getUserId(),
            //活动
            'active_id' => $input['id']
        ];
        //使用数量
        $use_count = $record_model->where($record_dis)->count();

        $data = [
            //价格
            'price'         => $active['price'],
            //红包个数
            'num'           => $active['num'],
            //总金额
            'total_price'   => round($active['price']*$active['num'],2),
            //使用条件
            'use_condition' => $active['use_condition'],
            //拉去多少人
            'user_num'      => $active['user_num'],
            //创建时间
            'create_time'   => date('Y-m-d H:i:s',$active['create_time']),
            //已经领取
            'use_num'       => $use_count,
            //剩余
            'y_num'         => $active['num'] - $use_count,
            //剩余金额
            'y_price'       => ($active['num'] - $use_count)*$active['price']
        ];
        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-10 13:33
     * @功能说明:展示到名片
     */
    public function showCard(){

        $input = $this->_input;
        //员工发放模型
        $staff_record_model = new staffRecord();
        //初始化
        $staff_record_model->initStaffRecord();
        //查询活动
        $active = $this->model->activeInfo(['id'=>$input['id']]);

        if(empty($active)){

            $this->errorMsg('活动未找到');

        }
        //已经领取个数
        $record_dis = [
            //员工
            'staff_id'  => $this->getUserId(),
            //活动
            'active_id' => $input['id']
        ];
        //查看是否添加到发放记录
        $have_show = $staff_record_model->where($record_dis)->find();

        if(empty($have_show)){

            $insert = [

                'uniacid'  => $this->_uniacid,
                //活动id
                'active_id'=> $active['id'],
                //员工id
                'staff_id' => $this->getUserId(),
                //总数
                'total_num'=> $active['num'],
                //单价
                'price'    => $active['price'],
                //总价
                'total_price' => round($active['price']*$active['num'],2),

            ];
            $res = $staff_record_model->recordAdd($insert);
        }

        $dis = [
            //活动id
            'active_id'=> $active['id'],
            //员工id
            'staff_id' => $this->getUserId(),
        ];

        //展示到首页
        if(empty($have_show)||$have_show['is_show']==0){

            $record_dis = [
                //状态
                'is_show'   => 1,
                //员工
                'staff_id'  => $this->getUserId(),
            ];
            $staff_record_model->where($record_dis)->update(['is_show'=>0]);
            //如果已经结束
            if(!empty($have_show)&&$have_show['status']!=0){

                $this->errorMsg('活动已经结束,不能展示到名片');

            }
            //展示
            $res = $staff_record_model->where($dis)->update(['is_show'=>1]);

        }else{
            //关闭
            $res = $staff_record_model->where($dis)->update(['is_show'=>0]);

        }

        return $this->success($res);
    }


    /**
     * User: chenniang
     * Date: 2019-12-18 14:30
     * @return void
     * descrption:列表
     */
    public function imgList(){

        $input = $this->_param;

        $img_model = new Img();
        //uniacid
        $dis[] = ['uniacid','=',$this->_uniacid];

        if(isset($input['type'])&&$input['type']!=999){

            $dis[] = ['type','=',$input['type']];
        }
        //查询
        $data  = $img_model->imgList($dis,$input['limit']);

        return $this->success($data);
    }

    /**
     * @author chenniang
     * @DataTime: 2020-03-09 18:48
     * @功能说明:添加活动
     */
    public function activeAdd(){

        $input = $this->_input;

        $core  = new WxSetting($this->_uniacid);

        $rest  = $core->wxContentRlue($input['title']);

        if($rest['errcode'] != 0){

            return $this->error('内容含有违法违规内容');
        }
        //使用类型
        $input['user_type']   = 2;
        //发布者
        $input['create_user'] = $this->getUserId();
        //uniacid
        $input['uniacid']     = $this->_uniacid;
        Db::startTrans();
        //添加
        $res   = $this->model->activeAdd($input);
        //订单号
        $out_trade_no = date( 'YmdHis' ) . '0' . $this->_uniacid. '0';

        $idlen        = strlen($res);
        //订单编号
        $order_code  = $out_trade_no . str_repeat( '0', 11 - $idlen ) . $res;
        //修改
        $this->model->where(['id'=>$res])->update(['order_code'=>$order_code]);

        $insert = [
            //uniacid
            'uniacid'    => $this->_uniacid,
            //员工id
            'staff_id'   => $this->getUserId(),
            //活动id
            'active_id'  => $res
        ];
        //添加到公司
        $this->company_model->companyAdd($insert);

        $admin_active_model = new \app\redbag\model\AdminActive();
        //添加到记录
        $admin_active_model->addRecord($input,[],[$this->getUserId()],$res);

        Db::commit();
        //支付类
        $pay_controller = new IndexWxPay($this->app);
        //用户
        $user           = $this->getUserInfo();
        //总金额
        $total_price    = round($input['price']*$input['num'],2);
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$user['openid'],$this->_uniacid,"红包活动",['type' => 'redbag' , 'out_trade_no' => $order_code],$total_price);

        if(!empty($jsApiParameters['code'])&&$jsApiParameters['code']==-1){

            $this->errorMsg($jsApiParameters['msg']);
        }

        $re_data['pay_list'] = $jsApiParameters;

        return $this->success($re_data);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-10 18:17
     * @功能说明:用户活动详情
     */
    public function selfActive(){

        $input = $this->_input;

        $active= $this->model->activeInfo(['id'=>$input['id']]);

        if(empty($active)){
            $this->errorMsg('活动未找到');
        }

        //邀请模型
        $invitation   = new Invitation();
        //记录模型
        $record       = new Record();
        //发放模型
        $staff_record = new staffRecord();
        //查看是否领取过
        $have  = $record->where(['user_id'=>$this->getUserId(),'active_id'=>$input['id'],'status'=>1])->find();
        //邀请人数
        $count = $invitation->where(['user_id'=>$this->getUserId(),'active_id'=>$active['id']])->count();
        //发放记录
        $stff_r= $staff_record->recordInfo(['staff_id'=>$input['staff_id'],'active_id'=>$input['id']]);

        if(empty($stff_r)){

            $this->errorMsg('该员工没有此红包权限');

        }

        if(!empty($have)){
            //已经领取
            $incon = 2;
        }else{

            $incon = $stff_r['status'];
            //如果正在进行中
            if(($incon==0&&$count>=$active['user_num'])||($incon==0&&$active['use_condition']==0)){

                $incon = 3;
            }
        }

        $data = [

            'use_condition' => $active['use_condition'],

            'num'           => $active['num'],

            'imgs'          => $active['imgs'],

            'use_count'     => $count,

            'user_num'      => $active['user_num'],

            'share_img'     => $active['share_img'],

            'id'            => $active['id'],

            'status'        => $incon,

            'title'         => $active['title'],

            'is_phone'      => $active['is_phone']

        ];

        return $this->success($data);

    }

    /**
     * @author chenniang
     * @DataTime: 2020-03-18 12:26
     * @功能说明:默认配置
     */
    public function defaultSetting(){

        $default = new DefaultSetting();

        $data = $default->settingInfo(['uniacid' => $this->_uniacid]);

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-10 18:39
     * @功能说明:进行中的活动（名片）
     */
    public function indexActive(){

        $input = $this->_input;

        $per  = new PermissionRedbag($this->_uniacid);

        $auth = $per->pAuth();

        if($auth!=true){

            return $this->success([]);

        }
        //员工发放模型
        $staff_record_model = new staffRecord();

        $dis = [
            'staff_id' => $input['staff_id'],

            'status'   => 0,

            'is_show'  => 1
        ];

        $record = $staff_record_model->recordInfo($dis);

        if(!empty($record)){

            $active = $this->model->where(['id'=>$record['active_id']])->field('id,cover,uniacid')->find();
        }

        $active = !empty($active)?$active:[];

        return $this->success($active);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-10 18:50
     * @功能说明:
     */
    public function shareNum(){

        $input = $this->_input;
        //如果是分享
        if($input['type']==1){
            //领取
            $this->getRedbag($input);
        }
        //员工发放模型
        $staff_record_model = new staffRecord();

        $dis = [

            'active_id' => $input['active_id'],

            'staff_id'  => $input['staff_id']

        ];
        $filet = $input['type'] ==1?'share_num':'pv';

        $res = $staff_record_model->recordInset($dis,$filet);

        return $this->success($res);
    }

    /**
     * @author chenniang
     * @DataTime: 2020-04-11 11:05
     * @功能说明:领取优惠券
     */
    public function getRedbag($input,$type=0){
        //查找活动
        $active = $this->model->activeInfo(['id'=>$input['active_id']]);

        if(empty($active)){

            $this->errorMsg('活动未找到');
        }
        //查看活动是否在进行中
        if($active['status']!=1){

            $this->errorMsg('活动已经结束!');

        }
        //员工到发放记录
        $staff_record = new staffRecord();

        $dis = [

            'staff_id' => $input['staff_id'],

            'active_id'=> $input['active_id']
        ];
        //查看该员工是否能发放
        $record = $staff_record->recordInfo($dis);

        if(empty($record)){

            $this->errorMsg('该员工没有此权限');

        }

        //查看是否在发放中
        if($record['status']!=0){

            $this->errorMsg('活动已经结束');
        }

        $dis = [
            'user_id' => $this->getUserId(),

            'active_id' => $input['active_id']
        ];
        //查看是否领取过
        $record = $this->record_model->recordInfo($dis);
        //领取过就不能分享了
        if(!empty($record['status'])&&$record['status']==1){

            $this->errorMsg('你已经领取过');

        }

        if(empty($record)){
            //添加
            $insert = [

                'uniacid'       => $this->_uniacid,

                'user_id'       => $this->getUserId(),

                'active_id'     => $input['active_id'],

                'price'         => $active['price'],

                'use_condition' => $active['use_condition'],

                'user_num'      => $active['user_num'],

                'staff_id'      => $input['staff_id'],

            ];

            $res = $this->record_model->recordAdd($insert);

            $record = $this->record_model->recordInfo($dis);
        }
        //查看活动是否有使用条件
        if($record['use_condition']==1){
            //邀请模型
            $invitation = new Invitation();
            //邀请人数
            $count = $invitation->getCount(['record_id'=>$record['id']]);

            if($count>=$record['user_num']&&$type==0){

                $this->errorMsg('邀请人数已满');

            }

            if($count<$record['user_num']&&$type==1){

                $this->errorMsg('邀请人数不足');

            }

        }

        return $record;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-11 13:33
     * @功能说明:领取打款
     */
    public function getPrice(){

        $input  = $this->_input;

        Db::startTrans();

        $is_staff = Db::name('longbing_card_user')->where(['id'=>$this->getUserId(),'is_staff'=>1])->find();

        if(!empty($is_staff)){

            $this->errorMsg('员工无法领取');
        }
        //检查状态
        $record = $this->getRedbag($input,1);

        $res = $this->record_model->where(['id'=>$record['id']])->update(['status'=>1,'update_time'=>time()]);

        $staff_record = new staffRecord();

        $has_dis[] = ['staff_id','=',$record['staff_id']];

        $has_dis[] = ['active_id','=',$record['active_id']];

        $has_dis[] = ['has_num','>',0];

        $result = $staff_record->where($has_dis)->update(['has_num'=>Db::raw('has_num-1')]);

        if($result!=1){

            $this->errorMsg('领取失败');

        }
        //初始化
        $staff_record->changeStatus($this->_uniacid);
        //邀请模型
        $invitation = new Invitation();
        //打款
        $res = $invitation->onCash($record);

        if($res['result_code']=='SUCCESS'&&$res['return_code']=='SUCCESS'){
        //if(1==1){

        }else{

            return $this->error(!empty($res['err_code_des'])?$res['err_code_des']:'你还未该权限');

        }

        Db::commit();

        return $this->success(1);

    }













}
